package com.example.listview;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;


import java.util.ArrayList;

public class StuAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<Student> studentArrayList;
    private IOnDelListener listener;

    public StuAdapter(Context context, ArrayList<Student> studentArrayList,IOnDelListener listener) {
        this.context = context;
        this.studentArrayList = studentArrayList;
        this.listener=listener;
    }

    public void ChangeData(ArrayList<Student> studentArrayList){
        this.studentArrayList=studentArrayList;
        notifyDataSetChanged();
    }


    @Override
    public int getCount() {
        return studentArrayList.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    int count = 0;


    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {
        Log.e("StuAdapter", "getview" + i + "count=" + count);
        if (view == null) {
            count++;
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            view = layoutInflater.inflate(R.layout.list_item, viewGroup, false);

            StuViewHolder holder = new StuViewHolder();

            holder.headImg = view.findViewById(R.id.Stu_Img);
            holder.nameView = view.findViewById(R.id.Stu_name);
            holder.ageView = view.findViewById(R.id.Stu_age);
            holder.Img_del=view.findViewById(R.id.Img_Del);
            view.setTag(holder);
        }

        Student stu = studentArrayList.get(i);

        StuViewHolder holder = (StuViewHolder) view.getTag();

        holder.headImg.setImageResource(stu.getImgId());
        holder.nameView.setText(stu.getName());
        holder.ageView.setText(String.valueOf(stu.getAge()));

        holder.Img_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                studentArrayList.remove(i);
                notifyDataSetChanged();
                listener.del(i);
            }
        });
        return view;
    }
}
